import { Request, toast, distance } from '../../utils/util.js'
let request = new Request()
const app = getApp()
Page({

  data: {
    selectedPortIndex : -1,
    selectedPriceIndex : 0,
    portStatusList : {0 : '空闲', 1 : '充电中', 2 : '故障'},
    chargeType : 0, //充电类型
    deviceNo : '',
    device : {},
    portList : [],
    optionsList : [],
    distance : ''
  },

  selectPort (e) {
    let currentIndex = this.data.selectedPortIndex
    let index = parseInt(e.currentTarget.dataset.index)
    if (currentIndex == index) {
      return
    }
    let port = this.data.portList[index]
    if(port.status != 0){
      return
    }

    this.setData({ selectedPortIndex : index})
  },

  selectPrice(e) {
    let currentIndex = this.data.selectedPriceIndex
    let index = parseInt(e.currentTarget.dataset.index)
    if (currentIndex == index) {
      return
    }

    this.setData({ selectedPriceIndex: index })
  },

  nav () {
    let device = this.data.device
    if (!device.longitude || !device.latitude) {
      toast('暂无位置信息')
      return
    }
    wx.openLocation({
      name: device.address,
      longitude: device.longitude,
      latitude: device.latitude
    })
  },

  contact () {
    let tel = this.data.device.service_telephone
    if(!tel){
      toast('暂无客服电话')
      return
    }
    wx.makePhoneCall({
      phoneNumber: tel,
      fail () {
        toast('拨号失败')
      }
    })
  },

  share () {
    wx.updateShareMenu({
      withShareTicket: true,
      success() { }
    })
  },

  submit (e) {
    let selectedPortIndex = this.data.selectedPortIndex
    let selectedPriceIndex = this.data.selectedPriceIndex
    if (selectedPortIndex < 0){
      toast('请选择插座')
      return
    }
    if (selectedPriceIndex < 0) {
      toast('请选择充电时长')
      return
    }

    let port = this.data.portList[selectedPortIndex]
    if (port.status != 0){
      return
    }
    let price = this.data.optionsList[selectedPriceIndex]

    let formData = {
      deviceNo: this.data.deviceNo,
      portId : port.port_id,
      quantity : price.q,
      formId: e.detail.formId
    }
    
    request.post('charge', res => {
      if(res.success){
        let orderId = res.data.order_id
        let wxparam = res.data.wxparam
        wxparam.success = () => {
          wx.showLoading({
            title: '正在请求'
          })
          let inter = setInterval(() => {
            request.post('chargeResult', res => {
              let status = res.data.status
              if (status == 0) {
                return
              }
              wx.hideLoading()
              clearInterval(inter)
              if(status == 1){ //充电成功
                wx.navigateTo({
                  url: '/pages/charing/index'
                })
              }else if(status == 3) { //充电失败
                wx.showModal({
                  showCancel : false,
                  title: '充电失败',
                  content: '充电失败，稍后将退款到微信'
                })
              }
            }, { id: orderId})
          }, 1000)
        }
        wxparam.fail = () => {
          toast('支付失败')
        }
        wx.requestPayment(wxparam)
      }else{
        toast(res.msg)
      }
    }, formData).showLoading()
  },

  onLoad: function (options) {
    let deviceNo = options.deviceNo || '19060300001'
    let portNo = options.portNo || 0
    request.get('device', res => {
      if(res.success){
        let data = res.data
        let chargePrice = data.charge_price
        if (chargePrice.options){
          if (!Array.isArray(chargePrice.options)){
            chargePrice.options = JSON.parse(chargePrice.options)
          }
        }
        
        let selectedPortIndex = -1

        if (portNo > 0) { //有指定端口
          let port = data.port[portNo - 1]
          if(port.status == 0) {
            selectedPortIndex = portNo - 1
          }
        }

        if (selectedPortIndex == -1) {
          for (let i = 0; i < data.port.length; i++) {
            if (data.port[i].status == 0) {
              selectedPortIndex = i
              break
            }
          }
        }

       

        let device = data.device
        if (device.longitude && device.latitude){
          wx.getLocation({
            success	: res => {
              let dst = distance([res.longitude, res.latitude], [device.longitude, device.latitude])
              this.setData({ distance : dst})
            }
          })
        }


        this.setData({ device: device, portList: data.port, optionsList: chargePrice.options, selectedPortIndex: selectedPortIndex, chargeType : chargePrice.charge_type})
      }else{
        toast(res.msg)
      }
    }, { deviceNo: deviceNo})
    this.setData({ deviceNo: deviceNo})

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})